/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.excel.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.star.framework.excel.handler.settings.DropdownValue;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;

/**
 * 单元格下拉选择值&校验<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public class CellDropdownHandler implements SheetWriteHandler, OrderHandler {

  @Getter @Setter private Map<Integer, List<String>> dropdownValues;

  private final DropdownValue setting;

  public CellDropdownHandler(Map<Integer, List<String>> dropdownValues) {
    this(dropdownValues, new DropdownValue());
  }

  public CellDropdownHandler(Map<Integer, List<String>> dropdownValues, DropdownValue setting) {
    this.dropdownValues = dropdownValues;
    this.setting = setting;
  }

  @Override
  public void afterSheetCreate(
      WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

    Sheet sheet = writeSheetHolder.getSheet();
    DataValidationHelper helper = sheet.getDataValidationHelper();
    if (CollectionUtil.isNotEmpty(dropdownValues)) {
      dropdownValues.forEach(
          (row, values) -> {
            // 起始行、终止行、起始列、终止列
            CellRangeAddressList range =
                new CellRangeAddressList(setting.getStartRow(), setting.getEndRow(), row, row);
            // 设置下拉框数据
            String[] listOfValues =
                CollectionUtil.isNotEmpty(values)
                    ? ArrayUtil.toArray(values, String.class)
                    : new String[] {};
            DataValidationConstraint constraint = helper.createExplicitListConstraint(listOfValues);
            DataValidation validation = helper.createValidation(constraint, range);
            // 处理Excel兼容性问题
            if (validation instanceof XSSFDataValidation) {
              validation.setSuppressDropDownArrow(true);
              validation.setShowErrorBox(true);
            } else {
              validation.setSuppressDropDownArrow(false);
            }

            sheet.addValidationData(validation);
          });
    }
  }

  @Override
  public int order() {
    return this.wrapper(OrderStrategyType.CELL_DROPDOWN);
  }
}
